package com.github.codemperor.gateway.config;

import com.alibaba.fastjson.JSONObject;
import com.github.codemperor.api.base.BaseCodeEnum;
import com.github.codemperor.api.base.BaseResponse;
import com.github.codemperor.core.token.context.CurrentUserContext;
import com.github.codemperor.gateway.context.FilterContext;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * filter需要继承次方法
 *
 * @author codemperor
 */
public abstract class BaseFilter extends ZuulFilter {

    private String contentType = "application/json;charset=UTF-8";
    private int failureCode = 403;

    protected void clearAllCustomContext() {
        // 断路操作后，清除线程内的数据
        FilterContext.currentUserInfo.remove();
        FilterContext.endingException.remove();

        FilterContext.apiFilterEnabled.remove();
        FilterContext.tokenFilterEnabled.remove();
        FilterContext.websiteTokenFilterEnabled.remove();
        FilterContext.costMillis.remove();

        CurrentUserContext.remove();
    }

    /**
     * 令牌验证失败，去登陆
     *
     * @param currentContext
     */
    protected void stopAndGoLogin(RequestContext currentContext, BaseCodeEnum e) {
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(failureCode);
        BaseResponse response = new BaseResponse(false, e);
        currentContext.setResponseBody(JSONObject.toJSONString(response));
        currentContext.getResponse().setContentType(contentType);
    }
}
